package service

import (
	"context"
	"encoding/json"
	"errors"
	mymux "github.com/gorilla/mux"
	"net/http"
	"strconv"
	"webdemo/src/go-kit/utils"
)

func DecodeUserRequest(ctx context.Context, request *http.Request) (interface{}, error) {
	/*if request.URL.Query().Get("uid") != ""{
		uid,_:=strconv.Atoi(request.URL.Query().Get("uid"))
		return UserRequest{
			Uid: uid,
		},nil
	}*/
	vars := mymux.Vars(request)
	method := request.Method
	if uid, ok := vars["uid"]; ok {
		uid, _ := strconv.Atoi(uid)
		return UserRequest{
			Uid:    uid,
			Method: method,
		}, nil
	}
	return nil, errors.New("参数错误")
}

func EncodeUserRequest(ctx context.Context, w http.ResponseWriter, res interface{}) error {
	w.Header().Set("Content-Type", "application/json")
	return json.NewEncoder(w).Encode(res)
}

func MyErrorEncoder(ctx context.Context, err error, w http.ResponseWriter) {
	contentType, body := "text/plain; charset=utf-8", []byte(err.Error())
	w.Header().Set("Content-Type", contentType)
	if myerr, ok := err.(*utils.MyError); ok {
		w.WriteHeader(myerr.Code)
		w.Write(body)
	} else {
		w.WriteHeader(500)
		w.Write(body)
	}

}
